package com.emode.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import com.emode.base.BaseDaoImpl;
import com.emode.entity.Bbsusers;
import com.emode.entity.SysGroup;
import com.emode.service.UserService;
@SuppressWarnings("unchecked")
public class UserServiceImpl extends BaseDaoImpl<Bbsusers> implements UserService{

	@Override
	public List findUsers(String string) {
		String hql = "from Bbsusers u where u.uname like %?%";
		return ht.find(hql,new Object[]{string});
	}	

	//更新登录时间
	@Override
	@Transactional
	public void updateLoginDate(Bbsusers users) {
		//whereHql = "";
		String hql = "update Bbsusers u set u.lastlogin=? where u.uid = ?";
		updateObj(hql,new Object[]{users.getLastlogin(),users.getUid()});
	}
	

	/* (non-Javadoc)
	 * @see com.emode.service.imp.IUserService#check(com.emode.entity.Bbsusers)
	 */
	@Override
	public Bbsusers find(Bbsusers user) {
		String whereHql = "";
		List paramsList = new ArrayList();
		if(StringUtils.isNotBlank(user.getUname())){
			whereHql = whereHql+" and o.uname=?";
			paramsList.add(user.getUname());
		}
		if(StringUtils.isNotBlank(user.getUpassword())){
			whereHql = whereHql+" and o.upassword=?";
			paramsList.add(DigestUtils.md5Hex(user.getUpassword()));
		}
		if(StringUtils.isNotBlank(user.getUemail())){
			whereHql = whereHql+" and o.uemail=?";
			paramsList.add(user.getUemail());
		}
		Object[] values = paramsList.toArray();
		List<Bbsusers> list = findObjectByConditionWithNoPage(whereHql, values);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
		
	}

	/*
	 * 用户注册 默认分配用户组
	 * 当一个用户添加成功，用户组人数加一
	 * @see com.emode.service.imp.IUserService#userReg(com.emode.entity.Bbsusers, com.emode.entity.SysGroup)
	 */
	@Transactional
	public void userReg(Bbsusers user,SysGroup group) {
		ht.save(user);
		user.getGroup().add(group);
		ht.update(user);
		String hql = "update SysGroup g set g.usernum = ? where g.groupid=?";
		updateObj(hql,new Object[]{group.getUsernum()+1,group.getGroupid()});
	}

	@Override
	public void updateSignTimes(Bbsusers user) {
		String hql = "update Bbsusers u set u.signtimes = ? where u.uid=?";
		updateObj(hql,new Object[]{user.getSigntimes()+1,user.getUid()});
	}

	@Transactional
	public void updateFollow(Bbsusers toUser,Bbsusers fromUser) {
		String hql = "update Bbsusers u set u.follows = ? where u.uid = ?";
		updateObj(hql, new Object[]{fromUser.getFollows()+1,fromUser.getUid()});
		String hql2 = "update Bbsusers u set u.followed = ? where u.uid = ?";
		updateObj(hql2, new Object[]{toUser.getFollowed()+1,toUser.getUid()});
	}



}
